package com.itic.mall.system.order.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.exports.ExportExcel;
import com.itic.appbase.applications.exports.ExportExcelWithTemplet;
import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.persistence.model.OrderExample;
import com.itic.mall.system.order.persistence.model.OrderExample.Criteria;
import com.itic.mall.system.order.persistence.model.OrderExpVo2;
import com.itic.mall.system.order.service.OrderService;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpress;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpressExample;
import com.itic.mall.system.orderexpress.service.OrderExpressService;
import com.itic.mall.system.orderproducts.persistence.model.OrderProducts;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsVo;
import com.itic.mall.system.orderproducts.service.OrderProductsService;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.product.service.ProductService;
import com.itic.mall.system.productproperty.persistence.model.ProductProperty;
import com.itic.mall.system.productproperty.service.ProductPropertyService;
import com.itic.mall.system.productpropertyvalue.persistence.model.ProductPropertyValue;
import com.itic.mall.system.productpropertyvalue.service.ProductPropertyValueService;
import com.itic.mall.system.productsku.persistence.model.ProductSku;
import com.itic.mall.system.productsku.service.ProductSkuService;
import com.itic.mall.system.user.persistence.model.MallUser;
import com.itic.mall.system.user.service.MallUserService;
import com.itic.mall.system.useraddress.persistence.model.UserAddress;
import com.itic.mall.system.useraddress.service.UserAddressService;
import com.itic.mall.system.user.persistence.model.MallUser;
import com.itic.mall.system.user.persistence.model.MallUserExample;


@Controller
@RequestMapping(value="/system/order")
public class OrderController
     extends BaseController {
	@Autowired
	private MallUserService mallUserService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderProductsService orderProductsService;
    @Autowired
    private OrderExpressService orderExpressService;
    @Autowired
	protected OutCommonService outCommonService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductSkuService productSkuService;
    /*@Autowired
    private CategoryService categoryService;*/
    
    @Autowired
    private ProductPropertyService productPropertyService;
    @Autowired
    private ProductPropertyValueService productPropertyValueService;
    
    //private static final String WULIU = "T_MALL_ORDER_WULIU";
    
    
    
    //导出常量
    private static final String TEMP = "bzmc";//备注名称
    private static final String DATALIST = "dataList";//数据常量
    
    //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////
    private static final String MODEL_NAME_CHINA = "订单管理";//中文名
    private static final String MODEL_NAME＿ENGLISH = "order";//英文名
    private static final String PAGE_COMMON_PATH = "/mall/system/order/order";//通用路径
    private static final String COMMON_URL = "/system/order/";//通用路径

    //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
   
    /*
     * 主页面
     */
    @RequestMapping(value="/init")
    public String init(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Main";
    }
    
    /*
     * 添加页面
     */
    @RequestMapping(value="/initAdd")
    public String initAdd(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Add";
    }
    
    /*
     * 添加页面
     */
    @RequestMapping(value="/wuliu")
    public String wuliu(String id ,Model model){
    	Order temp  = orderService.get(id);
    	String userAddressId = temp.getUserAddressId();
    	UserAddress userAddress = userAddressService.get(userAddressId);
    	
    	OrderExpressExample example = new OrderExpressExample();
    	example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andOrderIdEqualTo(id);
    	List<OrderExpress> list = orderExpressService.list(example);
    	if( list.size() > 0 ){
    		for( OrderExpress ttmp : list ){
    			ttmp.setExpressName(outCommonService.getNameByCode("T_MALL_ORDER_WULIU", ttmp.getExpressName()));
    		}
    	}
    	model.addAttribute("wuliuData",iticJsonMapper.toJson(list));
    	model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	model.addAttribute("detail", userAddress.getAddressDetail());
    	model.addAttribute("city", userAddress.getAddressCityAera());
    	model.addAttribute("phone", userAddress.getAddressPhone());
    	model.addAttribute("name", userAddress.getAddressName());
    	return PAGE_COMMON_PATH+"Wuliu";
    }
    
    /*
     * 编辑页面
     */
    @RequestMapping(value="/initEdit")
    public String initEdit(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		Order temp = orderService.get(id);
    		model.addAttribute("editData",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	return PAGE_COMMON_PATH+"Edit";
    }
    
    /*
     * 查看页面
     */
    @RequestMapping(value="/initView")
    public String initView(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		
    		Order temp  = orderService.get(id);
    		MallUser user = mallUserService.get(temp.getUserId());
    		temp.setUserId(user.getUserNickName());
    		//根据 订单ID 查找 所有的商品信息
    		/*OrderProductsExample example = new OrderProductsExample();
    		example.setOrderByClause("create_time desc");
    		Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andOrderIdEqualTo(id);
    		List<OrderProducts> list = orderProductsService.list(example);*/
    		
    		List<OrderProductsVo> list = orderProductsService.listByOrderId(id);
    		
    		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
    		
    		model.addAttribute("viewEditProducts",iticJsonMapper.toJson(list));
    		
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	
    	return PAGE_COMMON_PATH+"View";
    }
    
    @RequestMapping(value="initSendExpress")
    public String initSendExpress( String id, Model model ){
    	if( StringHelper.isNotBlank(id)){
    		Order temp = orderService.get(id);
    		model.addAttribute("orderId",id);
    		
    		UserAddress userAddress = userAddressService.get(temp.getUserAddressId());
    		model.addAttribute(userAddress);
    		model.addAttribute("name", userAddress.getAddressName());
    		model.addAttribute("phone", userAddress.getAddressPhone());
    		model.addAttribute("area", userAddress.getAddressCityAera());
    		model.addAttribute("detail", userAddress.getAddressDetail());
    		//model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else{
    		throw new ParameterErrorException();
    	}
    	return PAGE_COMMON_PATH + "SendExpress";
    }
    
    

    @RequestMapping(value="initBack")
    public String initBack( String id, Model model ){
        if( StringHelper.isNotBlank(id) ) {
    		
    		Order temp  = orderService.get(id);
    		MallUser user = mallUserService.get(temp.getUserId());
    		temp.setUserId(user.getUserNickName());
    		//根据 订单ID 查找 所有的商品信息
    		/*OrderProductsExample example = new OrderProductsExample();
    		example.setOrderByClause("create_time desc");
    		Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andOrderIdEqualTo(id);
    		List<OrderProducts> list = orderProductsService.list(example);*/
    		
    		List<OrderProductsVo> list = orderProductsService.listByOrderId(id);
    		
    		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
    		
    		model.addAttribute("viewEditProducts",iticJsonMapper.toJson(list));
    		
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	
    	return PAGE_COMMON_PATH + "Back";
    }
    
    
    //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
    
    /**
     * 添加模板管理数据
     * @param android
     * @return
     */
    @RequestMapping(value="/add")
    @ResponseBody
    public Map<String,String> add(Order Order){
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         result = orderService.add(Order);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /**
     * 添加模板管理数据
     * @param android
     * @return
     */
    @RequestMapping(value="/back")
    @ResponseBody
    public Map<String,String> back(String id,String note){
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         Order order = orderService.get(id);
         order.setId(id);
         order.setStatus("4");
         OrderProductsExample example = new OrderProductsExample();
         com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample.Criteria criteria = example.createCriteria();
         criteria.andIsEffectiveEqualTo(DBConst.TRUE);
         criteria.andOrderIdEqualTo(id);
         List<OrderProducts> list = orderProductsService.list(example);
         
         String temp = "退款备注：" + note ;
         String note2 = order.getNote();
         order.setNote( note2 += temp );
         
         result = orderService.back(order,list);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    /**
     * <p>Title:queryCondition </p>
     * <p>Description:封装查询条件 </p>
     * @param jzdw
     * @param jzdwExample
     * @return
     */
    private OrderExample queryCondition(HttpServletRequest request,Order temp,String userName,String userPhone) {
    	
    	
        OrderExample example = new OrderExample();
        // 参数处理
        // 按创建时间倒序
        example.setOrderByClause("CREATE_TIME DESC");
        // 按排列号顺序
        example.setOrderByClause("REORDER ASC");
        
        Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE );
        
        // 查询条件
        if ( null != temp ) {
        	
        	if( StringHelper.isNotBlank(temp.getOrderNum()) ){
        		criteria.andOrderNumLike("%"+temp.getOrderNum()+"%");
        	}
        	if( StringHelper.isNotBlank(temp.getStatus()) ){
        		criteria.andStatusEqualTo(temp.getStatus());
        	}
        	if( StringHelper.isNotBlank(temp.getId()) ){
        		criteria.andIdEqualTo(temp.getId());
        	}
        	if( StringHelper.isNotBlank(temp.getPayType()) ){
        		criteria.andPayTypeEqualTo(temp.getPayType());
        	}
        }
        //根据用户姓名获取用户信息
        if(StringHelper.isNotBlank(userName) || StringHelper.isNotBlank(userPhone)){
        	MallUserExample exampleuser = new MallUserExample();
        	com.itic.mall.system.user.persistence.model.MallUserExample.Criteria criteriauser = exampleuser.createCriteria();
        	criteriauser.andIsEffectiveEqualTo(DBConst.TRUE);
        	if(StringHelper.isNotBlank(userName)){
            	criteriauser.andUserNickNameEqualTo(userName);
        	}
        	if(StringHelper.isNotBlank(userPhone)){
            	criteriauser.andUserPhoneEqualTo(userPhone);
        	}
        	List<MallUser> listuser = mallUserService.list(exampleuser);
        	if(listuser.size()>0){
        		String userId = listuser.get(0).getId();
        		criteria.andUserIdEqualTo(userId);
        	}
        }
      
        return example;
    }
    
    /**
     * 
     * @param goldType
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(String userName,String userPhone,Order Order, HttpServletRequest request){
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        
        OrderExample example = this.queryCondition(request,Order,userName,userPhone);
        example.setOrderByClause("CREATE_TIME DESC");
        // 封装分页参数
        example = this.handlePageQuery(request, example);
        
        
        // 获取信息总条数
        int total = orderService.count(example);
        
        
        
        // 获取数据
        List<Order> list = orderService.list(example);
        if(list.size()>0){
        	for(Order temp:list){
        		String userNickName = "unknown";
        		if( StringHelper.isNotBlank(temp.getUserId() ) ){
        			MallUser user = mallUserService.get(temp.getUserId());
        			if( null!=user ){
        				if(StringHelper.isNotBlank(user.getUserNickName())){
        					userNickName = user.getUserNickName();
        				}
        			}
            		
        		}
        		temp.setUserId(userNickName);
        		
        		String isPay = "否";
        		if("1".equals(temp.getOrderIsPay())){
        		     isPay = "是";
        		}
        		temp.setOrderIsPay(isPay);
        	}
        }
        
        // 数据返回处理
        resultMap.put(IticConst.TOTAL_RECORDS, total);
        resultMap.put(IticConst.DISPLAY_RECORDS, total);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        resultMap.put(IticConst.DATA, list);
        return resultMap;

    }
    
    /**
     * 编辑保存
     * @param Order
     * @return
     */
    @RequestMapping(value="/edit")
    @ResponseBody
    public Map<String,String> edit(String delFileIds , Order order){
    
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         result = orderService.edit(order);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    

    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/del")
    @ResponseBody
    public Map<String, String> del(String id) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();


        if( StringHelper.isNotBlank(id) ){
            Order Order = new Order();
            Order.setId(id);
            result = orderService.delete(Order);
        }
        
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    
    /**
     * 订单发货
     * 
     */
    @RequestMapping(value = "/sendExpress")
    @ResponseBody
    public Map<String, String> sendExpress( OrderExpress express ) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();


        if( StringHelper.isNotBlank( express.getOrderId() ) ){
            result = orderExpressService.addAndUpdateOrder(express);
        }
        
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    
    /**
     * 过滤没有发货的商品信息
     * 
     */
    @RequestMapping(value = "/orderProducts")
    @ResponseBody
    public List<OrderProducts> orderProducts( String orderId ) {
    	List<OrderProducts> list = null;
    	if( StringHelper.isNotBlank( orderId ) ){
    		OrderProductsExample example = new OrderProductsExample();
    		com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample.Criteria criteria = example.createCriteria();
    	    criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	    criteria.andStatusEqualTo("1");//1为待发发货
    	    criteria.andOrderIdEqualTo(orderId);
    	    list = orderProductsService.list(example);
    	    if( list.size() > 0 ){
    	    	for( OrderProducts tmp : list ){
    	    		Product product = productService.get(tmp.getProductId());
    	    		tmp.setProductId(product.getName());
    	    	}
    	    }
    	}
    	return list;
    }
    
    
    
    
    @RequestMapping(value = "/exp")
    @ResponseBody
    public void exp(HttpServletRequest request, HttpServletResponse response,Order temp,String userName,String userPhone) {
    	 try {        	
         	 // 参数处理
    		 OrderExample example=new OrderExample();         
             example = this.queryCondition(request,temp,userName,userPhone);   
             List<OrderExpVo2> orders = new ArrayList<OrderExpVo2>();
             // 获取数据
             List<Order> list = orderService.list(example); 
             
             //查找订单信息
             if( list.size() > 0 ){
            	 for( Order tmp :list ){
            		 //String userNickName = mallUserService.get(tmp.getUserId()).getUserNickName();
            		 UserAddress address = userAddressService.get(tmp.getUserAddressId());
            		 
            		/* OrderExpress express = null ;
            		 if( StringHelper.isNotBlank(tmp.getWuliuId()) ){
            			 express = orderExpressService.get(tmp.getWuliuId());
            		 }*/
                	 
                	 //查找订单项
            		 OrderProductsExample exa = new OrderProductsExample();
            		 exa.setOrderByClause("CREATE_TIME DESC");
            		 com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample.Criteria criteria = exa.createCriteria();
                     criteria.andIsEffectiveEqualTo(DBConst.TRUE);
            		 criteria.andOrderIdEqualTo(tmp.getId());
                     List<OrderProducts> list2 = orderProductsService.list(exa);
                     for( OrderProducts ttmp: list2 ){
                    	
                    	 Product product = productService.get( ttmp.getProductId() );
                    	 ProductSku productSku = productSkuService.get(ttmp.getPropertySkuId());
                    	 //Category category = categoryService.get(product.getCategoryId());
                    	
                    	 String productPropertys = productSku.getProductPropertys();
                    	 
                    	 String propertysTmp="";
     					//如果商品有属性的话
     					String[] split = productPropertys.split(",");
     					
     					if( split.length > 0 ){
     						for(int i=0;i<split.length;i++){
         						String de = split[i];
         						if( de.contains(":") ){
         							String[] split2 = de.split(":");
             						if(split2.length>0){
             							propertysTmp += getPropertyName(split2[0])+":" ;
                 					    if( i==split.length-1 ){
                 					    	propertysTmp += getPropertyValueName(split2[1]) ;
                 					    }else{
                 					    	propertysTmp += getPropertyValueName(split2[1])+"," ;
                 					    }
             						}
         						}
         					 }
     					}
                    	 
                    	 OrderExpVo2 vo = new OrderExpVo2();
                    	 vo.setOrderId(tmp.getId());
                    	 vo.setOrderNum(tmp.getOrderNum());
                    	 vo.setProductName(product.getName());
                    	 vo.setPropertys(propertysTmp);
                    	 vo.setProductPrice(productSku.getProductOrginPrice());
                    	 //商品总价除以数量
                    	 vo.setProductHongbao(product.getProductHongbao());
                    	 vo.setTotalCount(tmp.getTotalProduct());
                    	 vo.setTotalMoney(tmp.getTotalMoney());
                    	 vo.setBuyNote(tmp.getNote());
                    	 vo.setSaleNote("");
                    	 vo.setUserId(tmp.getUserId());
                    	 vo.setAddressName(address.getAddressName());
                    	 vo.setAddressPhone(address.getAddressPhone());
                    	 if(address != null){
                        	 String addressCityAera = address.getAddressCityAera();
                        	 if(StringHelper.isNotBlank(addressCityAera)){
                        		 String[] split2 = addressCityAera.split(",");
                            	 String[] split3 = addressCityAera.split(" ");
                            	 if( split2.length==3 ){
                            		 vo.setAddressProvince(split2[0]);
                                	 vo.setAddressCity(split2[1]);
                                	 vo.setAddressArea(split2[2]);
                            	 }
                            	 if( split3.length==3 ){
                            		 vo.setAddressProvince(split3[0]);
                                	 vo.setAddressCity(split3[1]);
                                	 vo.setAddressArea(split3[2]);
                            	 }
                            	 if( split2.length==2 ){
                            		 vo.setAddressProvince(split2[0]);
                                	 vo.setAddressCity(split2[1]);
                                	 //vo.setAddressArea(split2[2]);
                            	 }
                            	 if( split3.length==2 ){
                            		 vo.setAddressProvince(split3[0]);
                                	 vo.setAddressCity(split3[1]);
                                	 //vo.setAddressArea(split3[2]);
                            	 }
                            	 vo.setAddressDetail(address.getAddressDetail());
                        	 }
                    	 }
                    	 vo.setCreateTime(DateHelper.formatDateTime(tmp.getCreateTime()));
                    	 vo.setPayTime(tmp.getPayTime());
                    	 orders.add(vo);
                     }
            	 }
             }
             
             //导出
             Map<String, Object> exportMap = new HashMap<String, Object>();
             exportMap.put(TEMP, MODEL_NAME＿ENGLISH);
             exportMap.put(DATALIST, orders);
             ExportExcel exportExcel = new ExportExcelWithTemplet();
             exportExcel.exportExcel(exportMap, request, response);
             
         } catch (Exception e) {
        	 throw new RuntimeException("[TempletController | exp 模板示例导出异常]");
         } 
    }
    
    public String getPropertyName(String id){
    	String name = "";
    	ProductProperty property = productPropertyService.get(id);
    	if(property != null){
    		name = property.getName();
    	}
    	return name;
    }
    
    public String getPropertyValueName(String id){
    	String name = "";
    	ProductPropertyValue propertyValue = productPropertyValueService.get(id);
    	if(propertyValue != null){
    		name = propertyValue.getPropertyValue();
    	}
    	return name;
    }
}